package work.chenxr.security.service.impl;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import work.chenxr.security.user.UserDetail;

import java.io.Serial;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Chenxr
 * @Date 2023/10/23
 * @Description 账号登录业务接口实现
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final SecurityUserDetailsServiceImpl securityUserDetailsService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 假装这里是从数据库查出来的
        Map<String, Object> dataSource = new HashMap<>() {
            @Serial
            private static final long serialVersionUID = -1L;

            {
                put("id", 10000);
                put("username", "admin");
                put("password", "{bcrypt}$2a$10$mW/yJPHjyueQ1g26WNBz0uxVPa0GQdJO1fFZmqdkqgMTGnyszlXxu");
                put("status", 1);
            }
        };

        // 查询当前用户名是否存在
        if (!dataSource.get("username").equals(username)) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        return securityUserDetailsService.getUserDetails(JSON.to(UserDetail.class, dataSource));
    }
}
